package user

import (
	"time"

	"fmt"

	pb "./protobuf"
	"change.tm/microservice"
	"golang.org/x/net/context"
	"google.golang.org/grpc"

	"errors"
)

var conn *grpc.ClientConn
var client pb.UserClient

func CreateToken(Userid string) (*pb.Reply, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	CreateTokenRequest := pb.CreateTokenRequest{}
	CreateTokenRequest.Userid = Userid
	fmt.Print(CreateTokenRequest)
	result, err := client.CreateToken(ctx, &CreateTokenRequest)
	// 进行远程调用
	if err != nil {
		return nil, err
	}
	// 超时取消本次会话
	return result, nil
}

func ValidateToken(Token string) (*pb.Reply, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	fmt.Print(Token)
	result, err := client.ValidateToken(ctx, &pb.ValidateTokenRequest{Token: Token})
	// 进行远程调用
	if err != nil {
		fmt.Print(err)
		return nil, errors.New("失败")
	}
	// 超时取消本次会话
	return result, nil
}

func Connect() (*grpc.ClientConn, error) {
	var err error
	conn, err = microservice.CreateSimpleClient("user")
	// 创建连接客户端
	client = pb.NewUserClient(conn)
	if err != nil {
		return nil, err
	}
	// defer conn.Close()
	// 函数结束时自动断开连接，在频繁通信时可以考虑不断开连接，对连接对象进行复用，提高效率。
	return conn, nil
}
